<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import DialogForm from '@/components/DialogForm.vue'
import { listEmployee, getEmployee, addEmployee, updateEmployee, delEmployee } from '@/api/employee'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return dateTime;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 表格数据
const tableData = ref([])
// 加载状态
const loading = ref(false)
// 表格列配置
const columns = [
  { prop: 'employeeName', label: '员工姓名', width: '120' },
  { 
    prop: 'role', 
    label: '员工角色', 
    width: '120', 
    formatter: (val) => (val === 0 ? '管理员' : '普通员工') 
  },
  { prop: 'phone', label: '联系电话', width: '120' },
  { prop: 'hireDate', label: '入职时间', width: '180', formatter: (val) => formatDateTime(val) }
]
// 搜索字段
const searchFields = ['employeeName', 'phone']

// 表单数据
const formData = reactive({
  id: null,
  employeeName: '',
  password: '',
  role: 1, // 默认为普通员工
  phone: '',
  hireDate: ''
})

// 表单字段配置 - 编辑模式
const editFormFields = [
  { prop: 'employeeName', label: '员工姓名', type: 'input', required: true },
  { 
    prop: 'password', 
    label: '登录密码', 
    type: 'input', 
    inputType: 'password', 
    required: true,
    showPassword: true
  },
  { prop: 'phone', label: '联系电话', type: 'input' },
  { prop: 'hireDate', label: '入职时间', type: 'date', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
]

// 表单字段配置 - 查看模式
const viewFormFields = [
  { prop: 'employeeName', label: '员工姓名', type: 'input', readonly: true },
  { 
    prop: 'role', 
    label: '员工角色', 
    type: 'radio', 
    options: [
      { label: '管理员', value: 0 },
      { label: '普通员工', value: 1 }
    ],
    disabled: true
  },
  { prop: 'phone', label: '联系电话', type: 'input', readonly: true },
  { prop: 'hireDate', label: '入职时间', type: 'input', readonly: true }
]

// 表单规则
const formRules = {
  employeeName: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 对话框配置
const dialogConfig = reactive({
  visible: false,
  title: '添加员工',
  isEdit: false,
  isView: false
})

// 获取员工列表
const getEmployeeList = async () => {
  loading.value = true
  try {
    const allEmployees = await listEmployee()
    // 过滤掉管理员，只显示普通员工
    tableData.value = allEmployees.filter(emp => emp.role === 1)
  } catch (error) {
    console.error('获取员工列表失败', error)
    ElMessage.error('获取员工列表失败')
  } finally {
    loading.value = false
  }
}

// 添加员工
const handleAdd = () => {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    if (key === 'role') {
      formData[key] = 1 // 固定为普通员工
    } else if (key === 'hireDate') {
      formData[key] = formatDateTime(new Date())
    } else {
      formData[key] = ''
    }
  })
  formData.id = null
  
  dialogConfig.title = '添加员工'
  dialogConfig.isEdit = false
  dialogConfig.isView = false
  dialogConfig.visible = true
}

// 编辑员工
const handleEdit = async (row) => {
  try {
    const res = await getEmployee(row.id)
    if (res) {
      // 检查是否为管理员
      if (res.role === 0) {
        ElMessage.warning('不能编辑管理员账户')
        return
      }
      
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = res[key]
      })
      
      dialogConfig.title = '编辑员工'
      dialogConfig.isEdit = true
      dialogConfig.isView = false
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取员工详情失败', error)
    ElMessage.error('获取员工详情失败')
  }
}

// 查看员工
const handleView = async (row) => {
  try {
    const res = await getEmployee(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = res[key]
      })
      
      dialogConfig.title = '查看员工'
      dialogConfig.isEdit = false
      dialogConfig.isView = true
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取员工详情失败', error)
    ElMessage.error('获取员工详情失败')
  }
}

// 删除员工
const handleDelete = async (row) => {
  try {
    // 检查是否为管理员
    if (row.role === 0) {
      ElMessage.warning('不能删除管理员账户')
      return
    }
    
    ElMessageBox.confirm('确定要删除该员工吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await delEmployee(row.id)
      ElMessage.success('删除成功')
      getEmployeeList()
    }).catch(() => {})
  } catch (error) {
    console.error('删除员工失败', error)
    ElMessage.error('删除员工失败')
  }
}

// 批量删除员工
const handleBatchDelete = async (rows) => {
  try {
    // 检查是否包含管理员
    if (rows.some(row => row.role === 0)) {
      ElMessage.warning('不能删除管理员账户')
      return
    }
    
    ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 名员工吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await Promise.all(rows.map(row => delEmployee(row.id)))
      ElMessage.success('批量删除成功')
      getEmployeeList()
    }).catch(() => {})
  } catch (error) {
    console.error('批量删除员工失败', error)
    ElMessage.error('批量删除员工失败')
  }
}

// 提交表单
const handleSubmit = async (data) => {
  try {
    // 确保角色为普通员工
    data.role = 1
    
    // 创建提交的数据副本，移除不需要的字段
    const submitData = { ...data }
    
    // 如果是编辑模式，不传递入职时间参数
    if (dialogConfig.isEdit) {
      // 编辑
      delete submitData.hireDate
      await updateEmployee(submitData)
      ElMessage.success('编辑成功')
    } else {
      // 添加
      await addEmployee(submitData)
      ElMessage.success('添加成功')
    }
    
    // 刷新列表
    getEmployeeList()
    // 关闭对话框
    dialogConfig.visible = false
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 初始化
onMounted(() => {
  getEmployeeList()
})
</script>

<template>
  <div class="employee-container">
    <el-card shadow="never" class="employee-card">
      <template #header>
        <div class="card-header">
          <h3>员工管理</h3>
          <div class="card-subtitle">
            <el-tag type="info">仅显示普通员工账户</el-tag>
          </div>
        </div>
      </template>
      
      <!-- 表格 -->
      <data-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :search-fields="searchFields"
        @add="handleAdd"
        @edit="handleEdit"
        @view="handleView"
        @delete="handleDelete"
        @batch-delete="handleBatchDelete"
        @refresh="getEmployeeList"
      />
    </el-card>
    
    <!-- 表单对话框 - 添加/编辑 -->
    <dialog-form
      v-if="!dialogConfig.isView"
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="editFormFields"
      :rules="formRules"
      @submit="handleSubmit"
    />
    
    <!-- 表单对话框 - 查看 -->
    <dialog-form
      v-else
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="viewFormFields"
      :readonly="true"
      :show-confirm-button="false"
      :cancel-button-text="'关闭'"
    >
      <template #hireDate="{ value }">
        {{ formatDateTime(value) }}
      </template>
    </dialog-form>
  </div>
</template>

<style scoped>
.employee-container {
  height: 100%;
}

.employee-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
}

.card-subtitle {
  font-size: 14px;
  color: #909399;
}

:deep(.el-card__body) {
  flex: 1;
  overflow: auto;
  padding: 15px;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}
</style> 